﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Sfs2X;
using Sfs2X.Core;
using Sfs2X.Entities;
using Sfs2X.Requests;
using Sfs2X.Logging;
using Sfs2X.Entities.Data;

public class GUIPlay : MonoBehaviour
{

    public GUIText nextNumber;
    public GUIText status;
    public GUIText moveMade;
    public GameObject button;
    public static int next_number;

    const int HEIGHT = 10, WIDTH = 10;

    private SmartFox sfConnectObj;
    private SFSObject receivedData;
    private string sfStatus;
    private GameObject[,] buttons;
    private float start_x = -5.5f;
    private float start_y = 3.5f;
    private int score = 0;

    void Awake()
    {
        if (SmartFoxConnection.IsInitialized)
        {
            sfConnectObj = SmartFoxConnection.Connection;
        }
        else
        {
            Application.LoadLevel("Connector");
        }

        // Register callback delegate
        sfConnectObj.AddEventListener(SFSEvent.CONNECTION_LOST, OnConnectionLost);
        sfConnectObj.AddEventListener(SFSEvent.OBJECT_MESSAGE, OnObjectMesssage);
        sfConnectObj.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
    }

    // Use this for initialization
    void Start()
    {
        SmartFoxConnection.Connection = sfConnectObj;

        moveMade.text = "Move made: " + score;
        
        next_number = 1;
        nextNumber.text = "Next number: " + next_number;

        receivedData = SmartFoxConnection.PersistentData;
        string opponent = receivedData.GetUtfString("opn");
        status.text = "Game started \nYour opponent is: " + opponent;

        InitMap();
        //ISFSObject mParams = new SFSObject();
        //mParams.PutInt("p_x", 0);
        //mParams.PutInt("p_y", 0);
        //mParams.PutInt("rID", sfConnectObj.LastJoinedRoom.Id);
        //sfConnectObj.Send(new ExtensionRequest(Commands.CMD_MOVE, mParams));
    }

    // Update is called once per frame
    void Update()
    {

    }

    void FixedUpdate()
    {
        sfConnectObj.ProcessEvents();
    }

    void InitMap()
    {

        buttons = new GameObject[HEIGHT, WIDTH];

        int number = 1;
        for (int i = 0; i < HEIGHT; i++)
        {
            for (int j = 0; j < WIDTH; j++)
            {
                buttons[i, j] = Instantiate(button) as GameObject;
                buttons[i, j].name = "NButton_" + number;
                buttons[i, j].transform.position = new Vector2(start_x, start_y);
                buttons[i, j].transform.GetChild(0).GetChild(0).GetComponent<tk2dTextMesh>().text = "" + number;
                number++;
                start_x += 0.5f;
            }
            start_x = -5.5f;
            start_y -= 0.5f;
        }
        Debug.Log("last number: " + number);
    }

    void OnConnectionLost(BaseEvent evt)
    {
        sfStatus = "Connection was lost, Reason: " + (string)evt.Params[MySFSParams.PARAM_REASON];
        status.text = sfStatus;
    }

    void OnObjectMesssage(BaseEvent evt)
    {
        User sender = evt.Params["sender"] as User;
        ISFSObject dataObj = evt.Params["message"] as SFSObject;
        // ignore who sent this message
        //if(sfConnectObj.MySelf.Id != sender.Id){
        // update next number
        next_number = dataObj.GetInt("n_n");
        nextNumber.text = "Next number: " + next_number;
        Debug.Log("next number: " + next_number);
        //}
    }

    void OnExtensionResponse(BaseEvent evt)
    {

        string cmd = evt.Params[MySFSParams.PARAM_CMD] as string;
        SFSObject dataObject = evt.Params[MySFSParams.PARAM_DATA] as SFSObject;
        Debug.Log("TV.Vinh User: extension response arrived cmd: " + cmd);
        switch (cmd)
        {
            // player move was made, change next_number & notify player's opponent
            case "ok":
                next_number++;
                nextNumber.text = "Next number: " + next_number;

                score++;
                moveMade.text = "Move made: " + score;

                ISFSObject mParams = new SFSObject();
                mParams.PutInt("n_n", next_number);
                sfConnectObj.Send(new ObjectMessageRequest(mParams));
                break;
            // 
            case "win":
                status.text = "Congratulation! You win.";
                next_number = -1;
                break;
        }

    }

    private void UnregisterSFSSceneCallbacks()
    {
        // This should be called when switching scenes, so callbacks from the backend do not trigger code in this scene
        sfConnectObj.RemoveAllEventListeners();
    }

    void OnDestroy()
    {
        UnregisterSFSSceneCallbacks();
    }
}
